package com.myshiro.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myshiro.pojo.User;
import com.myshiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author Jane
 * @date 2024-06-12 16:23
 */

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("-------------->认证开始");
        //逻辑认证 -->去数据库查


        UsernamePasswordToken loginUser = (UsernamePasswordToken) token;

        //匹配一个固定的账密
//        if (!"t365admin".equals(loginUser.getUsername())){
//            return null; //账户不存在
//        }
        //匹配数据库
        QueryWrapper<User> query = new QueryWrapper();
        query.eq("usr_Name",loginUser.getUsername());  //条件匹配数据库字段
        User user = userService.getOne(query);

//        user.setRoleName("管理员_玖谊");//角色

        if (null==user) throw new UnknownAccountException("账号不存在");

//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("","aaaaaa","");
        //密码校验的任务,就给了shiro
        //如果后期密码的验证逻辑越来越复杂,shiro来负责处理
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user
                ,user.getUsrPassword()//sql
                ,ByteSource.Util.bytes(user.getSalt())  //加盐
                ,this.getName());
        return info;

    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("-------------->授权开始");

        //指定静态的授权信息

        //先获取用户登录的信息
        User user = (User) principals.getPrimaryPrincipal();

        //授权对象
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.addRole(user.getRoleName());  //只要登录成功,我就给他这个角色所拥有的所有权限
        //添加单个的权限
       /* info.addStringPermission("用户列表");
      *//*  info.addStringPermission("用户添加");
        info.addStringPermission("用户修改");
        info.addStringPermission("用户删除");
*/
        if ("管理员_玖谊".equals(user.getRoleName())){
            info.addStringPermissions(Arrays.asList("用户添加"));//"用户修改","用户删除"
        }
        return info;
    }


}
